<style>
  .layui-input-inline{margin-top:10px;}
  .xxpayPopupDiv .layui-form-label {
     width:15% !important;
     margin-left:1%;
  }
  .xxpayPopupDiv .layui-input-inline {
     width: 33% !important;
  }
  #privateKeyDiv .layui-form-label {
    width: 120px !important;
  }
  #privateKeyDiv .layui-form-item{
    margin-bottom: 10px;
  }
  #privateKeyDiv .layui-input-inline {
    width: 190px !important;
    margin-top: 0;
  }
  #privateKeyDiv .layui-input-inline .layui-input{
    border: none;
    padding-left: 0;
    color: red;
  }
  #privateKeyDiv .layui-input-inline .verify-input{
    padding-left: 0;
    border-bottom: 1px solid #e6e6e6;
    border-radius: 0;
    color: black;
  }
</style>
<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>订单管理</cite></a>
    <a><cite>支付订单</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-tab layui-tab-brief">
      <ul class="layui-tab-title">
        <li class="layui-this">支付订单列表</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row">
          <form action="" id="exportForm" method="post">
            <input name="Authorization" id='exportHiddenInput' type="hidden"/>
            <div class="layui-form" style="float:right; margin-bottom: 10px;">
              <div id="timeDiv" class="layui-form-item" style="margin:0;">
                <div class="layui-input-inline">
                  <input type="text" name="mchId" id="searchMchId" placeholder="商户ID" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="payOrderId" id="searchPayOrderId" placeholder="支付订单号" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="mchOrderNo" id="searchMchOrderNo" placeholder="商户订单号" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="subject" id="searchSubject" placeholder="商品标题" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="number" name="amount" id="searchAmount" placeholder="支付金额（元）" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <select name="passageId" id="searchPassageId" lay-search="" lay-filter="passageIdFilter">
                    <option value="">支付通道</option>
                  </select>
                </div>
                <div class="layui-input-inline">
                  <select name="passageAccountId" id="searchPassageAccountId" lay-search="">
                    <option value="">通道子账户</option>
                  </select>
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="channelMchId" id="searchChannelMchId" placeholder="渠道商户" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <select name="productId" id="searchProductId" lay-search="">
                    <option value="-99">支付产品</option>
                  </select>
                </div>
                <!--<div class="layui-input-inline">-->
                  <!--<select name="type" id="searchProductType" placeholder="产品类型" lay-search="">-->
                    <!--<option value="-99">产品类型</option>-->
                    <!--<option value="1">收款</option>-->
                    <!--<option value="2">充值</option>-->
                  <!--</select>-->
                <!--</div>-->
                <div class="layui-input-inline">
                  <select name="status" id="searchStatus" lay-search="" >
                    <option value="-99">订单状态</option>
                    <option value="0">订单生成</option>
                    <option value="1">支付中</option>
                    <option value="2">支付成功</option>
                    <option value="-1">支付失败</option>
                    <option value="3">处理完成</option>
                    <option value="4">已退款</option>
                    <option value="-2">已关闭</option>
                  </select>
                </div>
                <div class="layui-input-inline">
                  <select name="type" id="isReissue" placeholder="是否补单" lay-search="">
                    <option value="-99">补单状态</option>
                    <option value="0">未补单</option>
                    <option value="1">已补单</option>
                  </select>
                </div>
                <div class="layui-input-inline" style="width: auto;">
                  <label class="layui-form-label">自动刷新</label>
                  <input type="checkbox" lay-filter="offlineRechargeAutoRefCheckbox" lay-skin="switch" />
                </div>
                <div class="layui-input-inline" style="width: auto;">
                  <a id="search" offlineRechargeAutoRef="false" subTime="9" initSubTime="9" class="layui-btn search" data-type="reload"><i class="layui-icon layui-icon-search"></i>搜索</a>
                </div>
                <!--<div class="layui-input-inline">-->
                  <!--<a type="submit" class="layui-btn"><i class="layui-icon layui-icon-download-circle"></i>导出</a>-->
                <!--</div>-->
                <div class="layui-input-inline" style="width: auto;">
                  <button id="dataStatistics" offlineRechargeAutoRef="false" class="layui-btn search" data-type="statistics"><i class="layui-icon layui-icon-chart-screen"></i>打开统计</button>
                </div>

             </div>
            </div>
            <div class="layui-form-item">
              <blockquote class="layui-elem-quote layui-hide dataCount" id="amountTip">
                提交订单数:<span id="allTotalCount" class="layui-badge layui-bg-blue loading"></span>
                订单总金额:<span id="allTotalAmount" class="layui-badge layui-bg-blue loading"></span>
                已付订单数:<span id="successTotalCount" class="layui-badge layui-bg-green loading"></span>
                已付总金额:<span id="successTotalAmount" class="layui-badge layui-bg-green loading"></span>
                未付订单数:<span id="failTotalCount" class="layui-badge loading"></span>
                未付总金额:<span id="failTotalAmount" class="layui-badge loading"></span>
              </blockquote>
              <blockquote class="layui-elem-quote layui-hide dataCount" id="amountTip2">
                商户总收款:<span id="successTotalMchIncome" class="layui-badge layui-bg-green loading"></span>
                代理商收入:<span id="successTotalAgentProfit" class="layui-badge layui-bg-green loading"></span>
                平台收入:<span id="successTotalPlatProfit" class="layui-badge layui-bg-green loading"></span>
                平台成本:<span id="successTotalChannelCost" class="layui-badge layui-bg-green loading"></span>
                成功率:<span id="successRate" class="layui-badge layui-bg-green loading"></span>
              </blockquote>
              <blockquote class="layui-elem-quote">
                <span class="layui-badge">待回调确认</span>：表示订单成功已经回调商户,等待商户确认结果  <span class="layui-badge">人工确认：是</span>：表示该笔订单已经收到支付成功通知,由于金额过大需要人工手动确认到账
              </blockquote>
            </div>
          </form>
          </div>
          <table id="XxPay_Mgr_PayOrder_dataAll" lay-filter="XxPay_Mgr_PayOrder_dataAll"></table>
        </div>

      </div>
    </div>
  </div>
</div>

<script type="text/html" id="xxpayBar">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail"><i class='layui-icon layui-icon-about'></i>查看</a>
  {{#  if(d.status == 1 || d.status == -2){ }}
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="queryChannel"><i class='layui-icon layui-icon-about'></i>查询</a>
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="reissue"><i class='layui-icon layui-icon-survey'></i>确认到账</a>
  {{#  } else { }}
  <a class="layui-btn layui-btn-primary layui-btn-xs layui-btn-disabled"><i class='layui-icon layui-icon-about'></i>查询</a>
  <a class="layui-btn layui-btn-primary layui-btn-xs layui-btn-disabled"><i class='layui-icon layui-icon-survey'></i>确认到账</a>
  {{#  } }}
</script>

<script>
layui.use(['admin', 'table', 'util', 'timePick', 'form'], function(){
  var $ = layui.$
  ,admin = layui.admin
  ,table = layui.table
  ,element = layui.element
  ,form = layui.form
  ,view = layui.view
  ,timePick = layui.timePick;

  timePick.init();  //第一个参数表示开始时间   第二个表示结束时间   0,0今天   -1,-1昨天   -7,0近一周   以此类推
  element.render('breadcrumb', 'breadcrumb');

  var switchStatus = "0";
  var router = layui.router();
  if(router.search.searchState){ //包含 状态初始值

      //选中状态
      $("#searchStatus option[value='"+router.search.searchState+"']").prop('selected', true);
  }

  $.setCountResult = function(mchId, productId, passageId, passageAccountId, payOrderId, mchOrderNo, productType, subject, amount, createTimeStart, createTimeEnd, channelMchId, isReissue) {
      $('.loading').html('<i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>');
      admin.req({
          type: 'get',
          url: layui.setter.baseUrl + '/pay_order/count',
          data: {
              mchId : mchId,
              productId : productId,
              passageId : passageId,
              passageAccountId : passageAccountId,
              payOrderId : payOrderId,
              mchOrderNo : mchOrderNo,
              productType : productType,
              channelMchId : channelMchId,
              subject: subject,
              amount: amount,
              isReissue: isReissue,
              createTimeStart : createTimeStart,
              createTimeEnd : createTimeEnd
          },
          error: function(err){
              layer.alert(JSON.stringify(err.field), {
                  title: '错误提示'
              })
          },
          success: function(res){
              if(res.code == 0){
                  // console.log(res.data.successTotalCount)
                  // console.log(res.data.allTotalCount)
                  $('#allTotalCount').html(res.data.allTotalCount);
                  $('#allTotalAmount').html("￥" + res.data.allTotalAmount/100.00);
                  $('#successTotalCount').html(res.data.successTotalCount);
                  $('#successTotalAmount').html("￥" + res.data.successTotalAmount/100.00);
                  $('#successTotalMchIncome').html("￥" + res.data.successTotalMchIncome/100.00);
                  $('#successTotalAgentProfit').html("￥" + (res.data.successTotalAgentProfit + res.data.successTotalParentAgentProfit)/100.00);
                  $('#successTotalPlatProfit').html("￥" + res.data.successTotalPlatProfit/100.00);
                  $('#successTotalChannelCost').html("￥" + res.data.successTotalChannelCost/100.00);
                  $('#failTotalCount').html(res.data.failTotalCount);
                  $('#failTotalAmount').html("￥" + res.data.failTotalAmount/100.00);
                  $('#successRate').html(parseFloat(res.data.successTotalCount/((res.data.allTotalCount)==0?1:res.data.allTotalCount)*100).toFixed(2) + "%");
              }
          }
      });
  };

  //导出参数初始化
  var tokenParamsName = layui.setter.request.tokenName;
  $('#exportHiddenInput').attr('name', tokenParamsName).val(layui.data(layui.setter.tableName)[tokenParamsName]);
  $('#exportForm').attr('action' , layui.setter.baseUrl+'/pay_order/exportExcel');

  // 加载支付产品
  admin.req({
    type: 'post',
    url: layui.setter.baseUrl + '/config/common/pay_product_all',
    error: function(err){
      layer.alert(err);
    },
    success: function(res){
      if(res.code == 0){
        var payProductList = res.data;
        //遍历赋值
        for(var i in payProductList){
          $("#searchProductId").append('<option value= '+payProductList[i].id+'>'+payProductList[i].productName+'</option>');
        }
        form.render('select');
      }
    }
  });

  // 加载支付通道
  admin.req({
    type: 'post',
    url: layui.setter.baseUrl + '/config/common/pay_passage_all',
    error: function(err){
      layer.alert(err);
    },
    success: function(res){
      if(res.code == 0){
        var payPassageList = res.data;
        //遍历赋值
        for(var i in payPassageList){
          $("#searchPassageId").append('<option value= '+payPassageList[i].id+'>'+payPassageList[i].passageName+'</option>');
        }
        form.render('select');
      }
    }
  });

  // 监听支付通道下拉选择值
  form.on('select(passageIdFilter)', function(data){
    // 清空通道子账户下拉框
    $("#searchPassageAccountId").find("option").remove();

    // 子账户下拉框赋值
    $("#searchPassageAccountId").append('<option value="">通道子账户</option>');
    loadPassageAccount(data.value);
  });

  // 加载通道子账户列表
  function loadPassageAccount(payPassageId) {
    admin.req({
      type: 'post',
      url: layui.setter.baseUrl + '/config/common/pay_passage_account',
      data: {
        payPassageId: payPassageId
      },
      error: function(err){
        layer.alert(err);
      },
      success: function(res){
        if(res.code == 0){
          var passageAccountList = res.data;
          //遍历赋值
          for(var i in passageAccountList){
            $("#searchPassageAccountId").append('<option value= '+passageAccountList[i].id+'>'+passageAccountList[i].accountName+'</option>');
          }
          form.render('select');
        }
      }
    });
  }

  var tplStatus = function(d){
    if(d.status == 0) {
      return "<span class='layui-badge layui-bg-blue'>订单生成</span>";
    }else if(d.status == 1) {
      return "<span class='layui-badge layui-bg-orange'>支付中</span>";
    }else if(d.status == 2) {
      return "<span class='layui-badge layui-bg-green'>支付成功</span>|<span style='color: red'>待回调确认</span>";
    }else if(d.status == -1) {
      return "<span class='layui-badge'>支付失败</span>";
    }else if(d.status == 3) {
      return "<span class='layui-badge layui-bg-green'>支付成功</span>|<span style='color: green'>已回调</span>";
    }else if(d.status == 4) {
      return "<span class='layui-badge'>已退款</span>";
    }else if(d.status == -2) {
        return "<span class='layui-badge layui-bg-gray'>已关闭</span>";
    }
  };

  var tplIsReConfirm = function(d){
      if(d.isReConfirm == 0) {
          return "<span class='layui-badge layui-bg-gray'>否</span>";
      }else if(d.isReConfirm == 1) {
          return "<span class='layui-badge'>要</span>";
      }
  };

    var reissueStatus = function(d){
    if(d.isReissue == 0) {
      return "-";
    }else if(d.isReissue == 1) {
      return "<span class='layui-badge layui-bg-blue'>已补</span>";
    }
  };

    // 初始化统计结果
    var createTimeStart = $('#createTimeStart').val();
    var createTimeEnd = $('#createTimeEnd').val();

  //用户列表
  table.render({
    elem: '#XxPay_Mgr_PayOrder_dataAll'
    ,url: layui.setter.baseUrl + '/pay_order/list' //用户列表接口
    ,toolbar: true //开启头部工具栏，并为其绑定左侧模板
    ,defaultToolbar: ['filter',{
        title: '导出'
        ,layEvent: 'export'
        ,icon: 'layui-icon-export'
      }] //, 'exports'
    ,where: {
        access_token: layui.data(layui.setter.tableName).access_token,
        createTimeStart: createTimeStart,
        createTimeEnd: createTimeEnd
    }
    ,id: 'tableReload'
    ,page: true
    ,cols: [[
      {type: 'checkbox', fixed: 'left'}
      ,{field: 'mchId', title: '商户ID', width: 100}
      ,{field: 'mchName', title: '商户名称'}
      ,{field: 'mchOrderNo', title: '商户单号'}
      ,{field: 'payOrderId', title: '支付单号', width: 220}
      ,{field: 'amount', title: '支付金额', templet: '<div>{{ d.amount/100 }}</div>', width: 100}
      ,{field: 'productName', title: '产品名称', width: 180}
      ,{field: 'channelMchId', title: '渠道商户', width: 180}
      ,{field: 'clientIp', title: '客户端IP', width: 100, hide: true}
      ,{field: 'device', title: '客户端设备', width: 100, hide: true}
      ,{field: 'status', title: '状态', templet: tplStatus, width: 180}
      ,{field: 'isReConfirm', title: '人工确认', templet: tplIsReConfirm, width: 100}
      ,{field: 'isReissue', title: '是否补单', templet: reissueStatus, align: 'center', width: 90}
      ,{field: 'createTime', title: '创建时间', templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>', width: 165}
      ,{field: 'edit', title: '操作', toolbar: '#xxpayBar', width: 260, fixed: 'right' }
    ]]
    ,skin: 'line'
  });

  //监听工具条
  table.on('tool(XxPay_Mgr_PayOrder_dataAll)', function(obj){
    var data = obj.data;
    if(obj.event === 'detail'){
      view.xxpayPopup("查看订单", "order/pay/view", {payOrderId: data.payOrderId}, {btn:false});
    }else if(obj.event === 'reissue') {
      view.xxpayPopup("确认到账", "order/pay/reissue",
              {payOrderId: data.payOrderId, amount: data.amount, mchOrderNo: data.mchOrderNo, createTimeConfirm: data.createTime},
              {btn:false, area: ['25%', '50%']});
    }else if(obj.event === 'queryChannel') {
        var payOrderId = data.payOrderId;
        layer.prompt({
            formType: 1,
            title: '查询上游状态，请输入平台超级密码：'
        }, function(value, index, elem){
            layer.close(index);
            var load = layer.msg('请求发送中...', {icon: 16,shade: 0.01,time: 9999999999});
            admin.req({
                type: 'post',
                url: layui.setter.baseUrl + '/pay_order/queryChannel',
                timeout: 1000 * 60,
                data:{
                    payOrderId: payOrderId,
                    password: value
                },
                error: function(err){
                    layer.close(load);
                    layer.alert(err);
                },
                success: function(res){
                    layer.close(load);
                    if(res.code == 0){
                        layer.alert("上游返回结果为：" + res.data);
                    }
                }
            });
        });
    }
  });

  //头工具栏事件
  table.on('toolbar(XxPay_Mgr_PayOrder_dataAll)', function(obj){
      var checkStatus = table.checkStatus(obj.config.id);
      console.log(obj.config)
      switch(obj.event){
          //自定义头工具栏右侧图标 - 提示
          case 'export':
              layer.confirm('确认导出该搜索条件下的列表吗？', function(index){
                  layer.close(index);
                  $("#exportForm").submit();
              });
              break;
      };
  });

  // 搜索
  var $ = layui.$, active = {
    reload: function(){
      var mchId = $('#searchMchId').val();
      var productId = $('#searchProductId').val();
      var payOrderId = $('#searchPayOrderId').val();
      var mchOrderNo = $("#searchMchOrderNo").val();
      var productType = $("#searchProductType").val();
      var createTimeStart = $('#createTimeStart').val();
      var createTimeEnd = $('#createTimeEnd').val();
      var status = $("#searchStatus").val();
      var isReissue = $("#isReissue").val();
      var passageId = $("#searchPassageId").val();
      var passageAccountId = $("#searchPassageAccountId").val();
      var channelMchId = $("#searchChannelMchId").val();
      var subject = $("#searchSubject").val();
      var amount = $("#searchAmount").val()*100;
      if (amount == 0) amount = null;

      if (switchStatus == 1) {
          $.setCountResult(mchId, productId, passageId, passageAccountId, payOrderId, mchOrderNo, productType, subject, amount, createTimeStart, createTimeEnd, channelMchId, isReissue);
      }
      //执行重载
      table.reload('tableReload', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        ,where: {
          mchId: mchId,
          productId: productId,
          payOrderId: payOrderId,
          mchOrderNo: mchOrderNo,
          productType: productType,
          passageId : passageId,
          passageAccountId : passageAccountId,
          status : status,
          isReissue : isReissue,
          channelMchId : channelMchId,
          subject : subject,
          amount: amount,
          createTimeStart : createTimeStart,
          createTimeEnd : createTimeEnd
        }
      });
    }, statistics: function(){
        if (switchStatus == "0") {
            $("#dataStatistics").html("<i class='layui-icon layui-icon-close-fill'></i>关闭统计");
            switchStatus = "1";
            var mchId = $('#searchMchId').val();
            var productId = $('#searchProductId').val();
            var payOrderId = $('#searchPayOrderId').val();
            var mchOrderNo = $("#searchMchOrderNo").val();
            var productType = $("#searchProductType").val();
            var createTimeStart = $('#createTimeStart').val();
            var createTimeEnd = $('#createTimeEnd').val();
            var status = $("#searchStatus").val();
            var isReissue = $("#isReissue").val();
            var passageId = $("#searchPassageId").val();
            var passageAccountId = $("#searchPassageAccountId").val();
            var channelMchId = $("#searchChannelMchId").val();
            var subject = $("#searchSubject").val();
            var amount = $("#searchAmount").val()*100;
            if (amount == 0) amount = null;

            $.setCountResult(mchId, productId, passageId, passageAccountId, payOrderId, mchOrderNo, productType, subject, amount, createTimeStart, createTimeEnd, channelMchId, isReissue);
            $(".dataCount").removeClass("layui-hide");
        }else {
            switchStatus = "0";
            $("#dataStatistics").html("<i class='layui-icon layui-icon-chart-screen'></i>打开统计");
            $(".dataCount").addClass("layui-hide");
        }
      }
  };

    $('.search').on('click', function() {
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
      return false;
    });

    form.on("switch(offlineRechargeAutoRefCheckbox)", function(data){
        if(data.elem.checked){ //开启
            $("#search[offlineRechargeAutoRef]").attr("offlineRechargeAutoRef", "true");
        }else{
            $("#search[offlineRechargeAutoRef]").attr("offlineRechargeAutoRef", "false");
        }
    });
  // 渲染表单
  form.render();
});

  //定时刷新  定时任务,  先清除， 后新增
  if(typeof(alipayCashInterval) != 'undefined'){
      window.clearInterval(alipayCashInterval);
  }

  var alipayCashInterval = window.setInterval('processRef()', 1000);  //每秒执行

  function processRef(){ //处理刷新任务

      var searchBtn = layui.jquery("#search[offlineRechargeAutoRef]");
      if(searchBtn.length > 0){

          if(searchBtn.attr("offlineRechargeAutoRef") != "true"){ //未开启
              return searchBtn.html('<i class="layui-icon layui-icon-search"></i>'+"搜索");
          }

          //开启定时刷新
          var subTime = searchBtn.attr('subTime') * 1;
          if(subTime <= 0){
              layui.jquery('#search').click();
              subTime = searchBtn.attr('initSubTime') * 1;
          }
          searchBtn.html('<i class="layui-icon layui-icon-search"></i>'+"搜索（"+subTime+"s）");
          subTime--;
          searchBtn.attr('subTime', subTime);

      }else{   //当查询控件不存在不在内，说明不是本页面，删除该定时任务器
          window.clearInterval(alipayCashInterval);
      }
  }

</script>